<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/layui-2.4.2/src/css/layui.css">
    <script type="text/javascript" src="/jquery/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/layui-2.4.2/src/layui.js"></script>
    <script type="text/javascript" src="/wangEditor.min.js"></script>
    <script type="text/javascript" src="/common.js"></script>
</head>
<body>
<div>

    <div class="layui-form layui-form-pane">
        <div class="layui-form-item row">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: auto;">国家</label>
                <div class="layui-input-inline layuiws">
                    <select name="country_select" lay-filter="country_select" class="country_select">
                    </select>
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label" style="width:auto;">城市</label>
                <div class="layui-input-inline layuiws">
                    <select name="city_select" lay-filter="city_select" class="city_select">
                    </select>
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label" style="width:auto;">状态</label>
                <div class="layui-input-inline layuiws">
                    <select name="status_select" class="status_select" lay-filter="status_select">
                        <option value="-1">全部</option>
                        <option value="1">在售</option>
                        <option value="0">停售</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="layui-form-item row">
            <div class="layui-inline">
                <label class="layui-form-label" style="width:auto">商品名称</label>
                <div class="layui-input-inline layuiws">
                    <input type="text" class="layui-input tripcar_name" name="tripcar_name"/>
                </div>
            </div>

            <div class="layui-inline">
                <button class="layui-btn" id="search">搜索</button>
                <button class="layui-btn" id="createTripCar">创建</button>
            </div>
        </div>
    </div>

    <div class="layui-row">
        <table id="tripcar_view" lay-filter="tripcar_view_filter">

        </table>
    </div>


</div>
<!--商品编辑浮层-->
<form class="layui-form" id="edit_tripcar" action="" style="display:none;margin-top: 30px;">
    <div class="layui-form-item">
        <label class="layui-form-label">商品名称</label>
        <div class="layui-input-block" style="margin-right: 20px;">
            <input type="text" name="name" lay-verify="name" autocomplete="off" placeholder="请输入商品名称"
                   class="layui-input">
            <input type="hidden" name="id" id="id"/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">支付蜜糖数</label>
        <div class="layui-input-block" style="margin-right: 20px;">
            <input type="text" name="honeySugar" placeholder="请输入支付蜜糖数" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">赠送勤劳度</label>
        <div class="layui-input-block" style="margin-right: 20px;">
            <input type="text" name="diligenceDegree" placeholder="请输入赠送勤劳度" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">赠送蜂蜜</label>
        <div class="layui-input-block" style="margin-right: 20px;">
            <input type="text" name="honey" placeholder="请输入赠送蜂蜜" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">类型</label>
        <div class="layui-input-block" style="margin-right:20px;">
            <select name="carType" lay-filter="tripcar_type">
                <option value="1">接机</option>
                <option value="2">送机</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">国家</label>
        <div class="layui-input-block layui-form" style="margin-right:20px;">
            <select name="country" lay-filter="country_form" id="country_form" class="country_form layui-form">
                <option th:each="c:${country}" th:value="${c.countryId}" th:text="${c.countryName}"></option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">城市</label>
        <div class="layui-input-block layui-form" style="margin-right:20px;">
            <select name="city" lay-filter="city_form" class="city_form">
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">车型</label>
        <div class="layui-input-block model_select" id="carModelId" name="carModelIds">
            <input type="hidden" name="carModelId" id="carModelIds"/>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-upload">
            <button type="button" class="layui-btn" id="btnPicture"
                    style="margin-left:40px;padding-left: 5px;padding-right: 5px;">商品图片上传
            </button>
            <br/>
            <div class="layui-row previewList" style="margin-left: 40px;margin-left: 40px;">

            </div>
            <input type="hidden" name="imagePathString" class="imagePathString"/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品详情</label>
        <div id="editor" class="layui-input-block" style="border:1px;padding-right:10px;">
        </div>
        <textarea name="description" id="description" hidden="hidden"></textarea>
        <!--<div class="layui-input-block" style="margin-right:20px;">-->
        <!---->
        <!--</div>-->
    </div>
    <br/>
</form>
<!--表格toobar模板-->
<script type="text/html" id="toolOper">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    {{#  if(d.status == 0){ }}
    <a class="layui-btn layui-btn-xs" lay-event="check">上架</a>
    {{#  } }}
    {{#  if(d.status == 1){ }}
    <a class="layui-btn layui-btn-xs" lay-event="check">下架</a>
    {{#  } }}
</script>
<script type="text/javascript">
    // var E = window.wangEditor;
    // var editor = new E('#editor');
    // var $text1 = $('#description');
    // // 配置服务器端地址
    // editor.customConfig.uploadImgServer = '/upload/image?typeId=1';
    // editor.customConfig.uploadFileName = 'file';
    // // editor.customConfig.uploadImgHeaders = {'Content-Type':'multipart/form-data'};
    // editor.customConfig.onchange = function (html) {
    //     // 监控变化，同步更新到 textarea
    //     $text1.val(html)
    // };
    // editor.customConfig.uploadImgHooks={
    //     customInsert:function (insertImg, result, editor) {
    //         insertImg(result.data);
    //         console.log();
    //     }
    // }
    // editor.create();
    // // 初始化 textarea 的值
    // $text1.val(editor.txt.html());
</script>
<script>
    var E = window.wangEditor;
    var editor = new E('#editor');
    var $text1 = $('#description');
    // 配置服务器端地址
    editor.customConfig.uploadImgServer = '/upload/image?typeId=2';
    editor.customConfig.uploadFileName = 'file';
    // editor.customConfig.uploadImgHeaders = {'Content-Type':'multipart/form-data'};
    editor.customConfig.onchange = function (html) {
        // 监控变化，同步更新到 textarea
        $text1.val(html)
    };
    editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result, editor) {
            insertImg(result.data);
            console.log();
        }
    }
    editor.create();
    // 初始化 textarea 的值
    $text1.val(editor.txt.html());
    layui.use(['element', 'table', 'upload', 'laytpl', 'form'], function () {
        var editInitCity = 0;
        var upload = layui.upload;
        var table = layui.table;
        var form = layui.form;
        //商品列表
        table.render({
            elem: '#tripcar_view',
            url: '/tripcar/list',
            page: true,
            limit: 10,
            limits: [10, 20, 50, 100],
            cols: [
                [
                    {field: 'id', title: '商品编号'},
                    {field: 'name', title: '商品名称'},
                    {field: 'honeySugar', title: '商品价格'},
                    {
                        field: 'status', title: '状态', templet: function (d) {
                            if (d.status === 0) return '停售';
                            if (d.status === 1) return '在售';
                        }
                    },
                    {field: 'right', align: 'center', toolbar: '#toolOper'}
                ]
            ],
            // request:{page:'page',limit:'limit'},
            response: {
                status: 'errorCode',
                countName: 'total',
                dataName: 'data'
            }
        });

        table.on('tool(tripcar_view_filter)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var status;
            if (layEvent === 'check') {
                if (data.status == 1) {
                    status = 0;
                } else {
                    status = 1;
                }
                $.ajax({
                    type: 'get',
                    data: {id: data.id, status: status},
                    url: '/tripcar/updateStatus',
                    cache: false,
                    success: function (data) {
                        if (data.success == true) {
                            $(".layui-laypage-btn").click();
                        }
                    }
                })
            }
            if (layEvent === 'edit') {
                if (data.status == 1) {
                    alert('在售商品不允许修改');
                    return;
                }
                $.ajax({
                    type: 'post',
                    data: {id: data.id},
                    url: '/tripcar/get',
                    cache: false,
                    dataType: 'json',
                    success: function (res) {
                        editTripCarFunc("编辑商品")
                        $("#edit_tripcar").find('input[name="name"]').val(res.data.name);
                        $("#edit_tripcar").find('input[name="honeySugar"]').val(res.data.honeySugar);
                        $("#edit_tripcar").find('input[name="id"]').val(res.data.id);
                        $("#edit_tripcar").find('input[name="diligenceDegree"]').val(res.data.diligenceDegree);
                        $("#edit_tripcar").find('input[name="honey"]').val(res.data.honey);
                        editInitCity = res.data.city;
                        // $("#edit_tripcar").find('input[name="country"]').val(res.data.country);
                        var select = 'dd[lay-value=' + res.data.country + ']';
                        $('.country_form').siblings("div.layui-form-select").find('dl').find(select).click();

                        // setCityByCountryId(res.data.country,$('.city_form'),res.data.city);
                        var country = res.data.country;
                        setCityByCountryId(country, $('.city_form'), editInitCity);
                        // $("#edit_tripcar").find('input[name="city"]').val(res.data.city);
                        // $("#description").val(res.data.description);
                        $(".imagePathList").val('');
                        editor.txt.clear();
                        editor.txt.append(res.data.description);
                        for (var i = 0; i < res.data.imagePaths.length; i++) {
                            var img = '<div style="width:80px;float:left;display:inline-block;"><img class="layui-col-md1 src_path" style="width:80px;height:80px;" src="' + res.data.imagePaths[i].path + '"/>' +
                                '<p><a href="javascript:" class="delImg">删除</a></p></div>';
                            $(".previewList").append(img);
                        }
                    }
                });
                // $("#status").attr(data.)

            }
        });
        $("#search").on('click', function () {
            table.reload('tripcar_view', {
                url: '/tripcar/list',
                where: {
                    country: $('.country_select').val(),
                    city: $('.city_select').val(),
                    status: $('.status_select').val(),
                    name: $('.tripcar_name').val()
                }
            });
        });

        var imagePathList = new Array();

        $(document).on('click', '.delImg', function () {
            currentItem = $(this).parent().parent().remove();
        });
        $('#createTripCar').on('click', function () {
            setCarModel();
            setCityByCountryId($('.country_form').val(), $('.city_form'));
            editTripCarFunc("创建商品");
        });
        //图片上传
        upload.render({
            elem: '#btnPicture'
            , url: '/upload/image',
            data: {typeId: 2}
            , before: function (obj) {
                alert("蜜蜂");
            }
            , done: function (res) {
                //上传完毕
                if (res.success == true) {
                    var img = '<div style="width:80px;float:left;display:inline-block;"><img class="layui-col-md1 src_path" style="width:80px;height:80px;" src="' + res.data + '"/>' +
                        '<p><a href="javascript:" class="delImg">删除</a></p></div>';
                    $(".previewList").append(img);
                    // imagePathList.push(res.data);
                }
            }
        });
        var editTripCarFunc = function (title) {

            layer.open({
                type: 1,
                title: title,
                area: ['880px', '600px'],
                content: $("#edit_tripcar"),
                btn: ['保存', '取消'],
                btnALign: 'c',
                yes: function (index, layero) {

                    var pathList;
                    $.each($(".src_path"), function (index, item) {
                        if (index > 0) {
                            pathList += ';' + $(item).attr('src');
                        } else {
                            pathList = $(item).attr('src');
                        }
                    });

                    $('.imagePathString').attr('value', pathList);

                    // if($("#edit_tripcar").find('input[name="name"]').val().length

                    var name = $("#edit_tripcar").find('input[name="name"]').val();
                    if (name == undefined || name == '' || name.length > 30) {
                        alert('商品名称不允许为空，且长度不能大于30');
                        return;
                    }

                    if (!checkDecimal2($("#edit_tripcar").find('input[name="diligenceDegree"]').val())) {
                        alert('勤劳度数小数点不超过两位的正数');
                        return;
                    }

                    if (!checkDecimal2($("#edit_tripcar").find('input[name="honey"]').val())) {
                        alert('蜂蜜数小数点不超过两位的正数');
                        return;
                    }

                    var arr = [];
                    $("input:checkbox[name='carModelId']:checked").each(function (i) {
                        arr[i] = $(this).val();
                    });
                    $('#carModelId').attr('value', arr);
                    if ($("#carModelId").val() == '') {
                        alert('请选择车型');
                        return;
                    }
                    alert($('#carModelId').val());
                    alert($('#edit_tripcar').serialize());
                    // if(pathList==undefined||pathList==''){
                    //     alert('请上传商品图片');
                    //     return;
                    // }

                    $.ajax({
                        type: 'post',
                        data: $('#edit_tripcar').serialize(),
                        url: '/tripcar/save',
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            layer.closeAll();
                            $(".layui-laypage-btn").click()
                        }
                    });
                },
                end: function () {
                    $("#edit_tripcar").find('input[name="name"]').val('');
                    $("#edit_tripcar").find('input[name="honeySugar"]').val('');
                    $("#edit_tripcar").find('input[name="id"]').val('');
                    $("#edit_tripcar").find('input[name="diligenceDegree"]').val('');
                    $("#edit_tripcar").find('input[name="honey"]').val('');
                    // $("#description").val(res.data.description);
                    $(".previewList").html('');
                    $(".imagePathList").val('');
                    editor.txt.clear();
                    layer.closeAll();
                }
            });

        };

        $.ajax({
            type: 'post',
            url: '/tripcar/getCountry',
            cache: false,
            dataType: 'json',
            success: function (res) {
                if (res.success == true) {
                    var optionHtml = '';
                    $(".country_select").append('<option value="0">请选择</option>');
                    for (var i = 0; i < res.data.length; i++) {
                        optionHtml += '<option value="' + res.data[i].countryId + '">' + res.data[i].countryName + '</option>';
                    }
                    $(".country_select").append(optionHtml);
                    form.render('select');
                }
            }
        });
        form.on('select(country_select)', function (data) {
            var countryId = $('.country_select').val();
            setCityByCountryId(countryId, $('.city_select'), 0);
        });

        function setCarModel() {
            $(".model_select").html('');
            $.ajax({
                type: 'post',
                url: '/carModel/getCarModels',
                cache: false,
                dataType: 'json',
                success: function (res) {
                    if (res.success == true) {
                        var optionHtml = '';
                        for (let i = 0; i < res.data.length; i++) {
                            optionHtml += '<input type="checkbox" name="carModelId" value="' + res.data[i].modelId + '" title="' + res.data[i].modelName + '"/>';
                        }
                        $(".model_select").append(optionHtml);
                        form.render('checkbox');
                    }
                }
            });
        }

        form.on('select(country_form)', function (data) {
            var countryId = $('.country_form').val();
            // if(editInitCity==0){
            setCityByCountryId(countryId, $('.city_form'), 0);
            // }
        });

        function setCityByCountryId(countryId, citySelect, editInitCity) {
            $.ajax({
                type: 'post',
                url: '/tripcar/getCity',
                data: {countryId: countryId},
                cache: false,
                dataType: 'json',
                success: function (citys) {
                    if (citys.success == true) {
                        var optionHtml = '';
                        if (editInitCity <= 0) {
                            optionHtml = '<option value="0">未选择</option>';
                        }
                        if (citys.data != null && citys.data.length > 0) {
                            for (var i = 0; i < citys.data.length; i++) {
                                optionHtml += '<option value="' + citys.data[i].cityId + '">' + citys.data[i].cityName + '</option>';
                            }
                        } else {
                            optionHtml = '<option value="0">未选择</option>';
                        }
                        $(citySelect).html('');
                        $(citySelect).append(optionHtml);
                    }
                    form.render('select');
                    if (editInitCity > 0) {
                        //$(citySelect).val(selectdCityId);
                        var select = 'dd[lay-value=' + editInitCity + ']';
                        $(citySelect).siblings("div.layui-form-select").find('dl').find(select).click();
                        //editInitCity=0;
                    }
                    // form.render('select','city_form');
                }
            });
        }


    });
</script>

</body>
</html>